// 播放历史管理工具
class HistoryManager {
  constructor() {
    this.storageKey = 'music_history'
    this.maxHistoryCount = 100 // 最大历史记录数量
  }

  // 获取用户播放历史
  getUserHistory(userId) {
    try {
      const allHistory = uni.getStorageSync(this.storageKey) || {}
      const userHistory = allHistory[userId] || []
      
      // 按播放时间倒序排列（最新的在前）
      return userHistory.sort((a, b) => new Date(b.playTime) - new Date(a.playTime))
    } catch (error) {
      console.error('获取播放历史失败:', error)
      return []
    }
  }

  // 添加播放记录
  addToHistory(userId, songInfo) {
    try {
      const allHistory = uni.getStorageSync(this.storageKey) || {}
      let userHistory = allHistory[userId] || []
      
      // 检查是否已存在相同歌曲
      const existingIndex = userHistory.findIndex(item => item.songId === songInfo.songId)
      
      if (existingIndex !== -1) {
        // 如果已存在，更新时间并移到最前面
        userHistory[existingIndex].playTime = new Date().toISOString()
        userHistory.splice(existingIndex, 1)
        userHistory.unshift(userHistory[existingIndex])
      } else {
        // 如果不存在，添加新记录
        const historyItem = {
          id: Date.now() + Math.random(),
          songId: songInfo.songId,
          songTitle: songInfo.songTitle,
          artist: songInfo.artist,
          coverUrl: songInfo.coverUrl,
          playTime: new Date().toISOString()
        }
        userHistory.unshift(historyItem)
      }
      
      // 限制历史记录数量
      if (userHistory.length > this.maxHistoryCount) {
        userHistory = userHistory.slice(0, this.maxHistoryCount)
      }
      
      // 保存到本地存储
      allHistory[userId] = userHistory
      uni.setStorageSync(this.storageKey, allHistory)
      
      return true
    } catch (error) {
      console.error('添加播放历史失败:', error)
      return false
    }
  }

  // 从历史记录中移除
  removeFromHistory(userId, songId) {
    try {
      const allHistory = uni.getStorageSync(this.storageKey) || {}
      let userHistory = allHistory[userId] || []
      
      userHistory = userHistory.filter(item => item.songId !== songId)
      
      allHistory[userId] = userHistory
      uni.setStorageSync(this.storageKey, allHistory)
      
      return true
    } catch (error) {
      console.error('移除播放历史失败:', error)
      return false
    }
  }

  // 清空播放历史
  clearHistory(userId) {
    try {
      const allHistory = uni.getStorageSync(this.storageKey) || {}
      allHistory[userId] = []
      uni.setStorageSync(this.storageKey, allHistory)
      
      return true
    } catch (error) {
      console.error('清空播放历史失败:', error)
      return false
    }
  }

  // 获取最近播放的歌曲
  getRecentSongs(userId, count = 10) {
    try {
      const userHistory = this.getUserHistory(userId)
      return userHistory.slice(0, count)
    } catch (error) {
      console.error('获取最近播放歌曲失败:', error)
      return []
    }
  }

  // 初始化测试数据
  initTestData(userId) {
    const testHistory = [
      {
        id: 1,
        songId: 1,
        songTitle: '骄傲',
        artist: '王源',
        coverUrl: 'https://ai-public.mastergo.com/ai/img_res/9b30f4ee0302b8d25ce0fca941c22eca.jpg',
        playTime: new Date(Date.now() - 30 * 60 * 1000).toISOString() // 30分钟前
      },
      {
        id: 2,
        songId: 2,
        songTitle: '夜的钢琴曲',
        artist: '石进',
        coverUrl: 'https://ai-public.mastergo.com/ai/img_res/c1ce38ecf2bd6fbe61281df433ca6b50.jpg',
        playTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() // 2小时前
      },
      {
        id: 3,
        songId: 3,
        songTitle: '童话镇',
        artist: '陈一发儿',
        coverUrl: 'https://ai-public.mastergo.com/ai/img_res/f9fc38e361ab67a35c0e5506eddd71df.jpg',
        playTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() // 1天前
      },
      {
        id: 4,
        songId: 4,
        songTitle: '起风了',
        artist: '买辣椒也用券',
        coverUrl: 'https://ai-public.mastergo.com/ai/img_res/45336b12831b6117c08a852940c79512.jpg',
        playTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString() // 3天前
      }
    ]

    try {
      const allHistory = uni.getStorageSync(this.storageKey) || {}
      allHistory[userId] = testHistory
      uni.setStorageSync(this.storageKey, allHistory)
      return true
    } catch (error) {
      console.error('初始化测试数据失败:', error)
      return false
    }
  }
}

// 创建单例实例
const historyManager = new HistoryManager()

export default historyManager